<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\data\Pagination;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use common\models\User;
use backend\models\UserForm;
use common\models\Employees;
use backend\models\UserDataForm;
use yii\helpers\Json;
use yii\web\ForbiddenHttpException;
use common\models\AuthAssignment;
use common\models\AuthItem;
use common\models\AuthItemChild;
use backend\models\UserAuthForm;
use backend\models\RoleForm;

/**
 * User controller
 */
class UserController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['create', 'datalist', 'suspend', 'active', 'assign', 'authlist', 'getauth', 'updaterole'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionCreate($id=null)
    {
        if(!Yii::$app->user->can('createAdmin')){
            throw new ForbiddenHttpException('对不起，您现在还没获得此操作的权限');
        }

        $model = new UserForm($id);

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->addOrUpdate()) {

                return $this->redirect(['user/datalist']);
            }
        }
        $employee = Employees::find()->where(['status' => Employees::ACTIVE_STATUS])->asArray()->all();

        return $this->render('create', ['model' => $model, 'employee' => $employee]);
    }

    public function actionDatalist()
    {
        if(!Yii::$app->user->can('updateAdmin')){
            throw new ForbiddenHttpException('对不起，您现在还没获得此操作的权限');
        }

        $data_form = new UserDataForm;
        $data = User::find();
        if ($data_form->load(Yii::$app->request->get()) && $data_form->validate()) {
            $data = $data_form->query();
        }

        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => '10']);
        $model = $data->offset($pages->offset)->limit($pages->limit)->all();
        $emp_arr = Employees::find()->where(['status' => Employees::ACTIVE_STATUS])->asArray()->all();
        $employee = ArrayHelper::map($emp_arr, 'id', 'realname');

        return $this->render('datalist', ['model' => $model, 'pages' => $pages, 'employee' => $employee]);
    }

    /*
    * 账号停用
     */
    public function actionSuspend()
    {
        $uid = Yii::$app->request->get()['uid'];
        $user = User::findOne($uid);
        if ($user) {
            $user->status = User::STATUS_DELETED;
            if ($user->save(false)) {

                $re_arr = [
                    'flag' => true
                ];

                return JSON::encode($re_arr);
            }
        }

        $re_arr = [
            'flag' => flase
        ];

        return JSON::encode($re_arr);
    }

    /*
    * 账号启用
     */
    public function actionActive()
    {
        $uid = Yii::$app->request->get()['uid'];
        $user = User::findOne($uid);
        if ($user) {
            $user->status = User::STATUS_ACTIVE;
            if ($user->save(false)) {

                $re_arr = [
                    'flag' => true
                ];

                return JSON::encode($re_arr);
            }
        }

        $re_arr = [
            'flag' => flase
        ];

        return JSON::encode($re_arr);
    }

    /*
    * 分配用户权限
     */
    public function actionAssign($uid=null)
    {
        $model = new UserAuthForm();
        $roles = AuthItem::find()->where(['type' => 1])->andWhere(['<>', 'data', ""])->all();
        $auth = AuthItem::find()->where(['type' => 2])->all();
        $username = User::findOne($uid)->username;
        $auth_assignment = AuthAssignment::find()->where(['user_id' => $uid])->one();
        $auth_item_child = [];
        if ($auth_assignment) {
            $auth_item_child = AuthItemChild::find()->where(['parent' => $auth_assignment->item_name])->asArray()->all();
            $re = [];
            foreach ($auth_item_child as $key => $val) {
                $re[$key] = $val['child'];
            }
            $auth_item_child = $re;
        }
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->assignAuth()) {

                return $this->redirect(['user/datalist']);
            }
        }

        return $this->render('assign', ['uid' => $uid,'roles' => $roles, 'auth' => $auth, 'username' => $username, 'auth_item_child' => $auth_item_child]);
    }

    /*
    * 角色列表
     */
    public function actionAuthlist()
    {
        if(!Yii::$app->user->can('assignRole')){
            throw new ForbiddenHttpException('对不起，您现在还没获得此操作的权限');
        }

        $roles = AuthItem::find()->where(['type' => 1])->andWhere(['<>', 'data', ""])->all();
        $auth = AuthItem::find()->where(['type' => 2])->all();

        return $this->render('authlist', ['roles' => $roles, 'auth' => $auth]);
    }

    /*
    * 异步获取选中的权限
     */
    public function actionGetauth()
    {
        $role = trim(Yii::$app->request->get()['role']);
        $auth_item_child = AuthItemChild::find()->where(['parent' => $role])->all();
        $checked = [];
        foreach ($auth_item_child as $key => $val) {
            $checked[$key] = $val->child;
        }
        $auth = AuthItem::find()->where(['type' => 2])->all();
        $roles = ArrayHelper::map($auth, 'name', 'description');

        return JSON::encode([
                'checked' => $checked,
                'roles' => $roles
            ]);
    }

    /*
    * 更新角色
     */
    public function actionUpdaterole()
    {
        $model = new RoleForm;

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->update()) {
                Yii::$app->session->setFlash('success', '角色更新成功');

                return $this->redirect(['user/authlist']);
            }
        }

        Yii::$app->session->setFlash('error', '角色更新失败');

        return $this->redirect(['user/authlist']);
    }

}    